package com.stone.framework.task.service.impl;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.stone.framework.core.util.Beans;
import com.stone.framework.message.task.JobExecutionPageReqBody;
import com.stone.framework.message.task.JobExecutionPageResBody;
import com.stone.framework.message.task.StepExecutionResBody;
import com.stone.framework.task.entity.JobExecutionParams;
import com.stone.framework.task.entity.StepExecution;
import com.stone.framework.task.mapper.JobExecutionMapper;
import com.stone.framework.task.mapper.JobExecutionParamsMapper;
import com.stone.framework.task.mapper.StepExecutionMapper;
import com.stone.framework.task.service.ExecutionService;

@Service
@Transactional(readOnly = true)
public class ExecutionServiceImpl implements ExecutionService {

    @Autowired
    private JobExecutionMapper jobExecutionMapper;

    @Autowired
    private JobExecutionParamsMapper jobExecutionParamsMapper;

    @Autowired
    private StepExecutionMapper stepExecutionMapper;

    @Override
    public IPage<JobExecutionPageResBody> queryJobPage(JobExecutionPageReqBody reqBody,
        Page<JobExecutionPageResBody> page) {
        IPage<JobExecutionPageResBody> result = jobExecutionMapper.selectPage(page,
            new QueryWrapper<JobExecutionPageReqBody>().eq("bji.JOB_NAME", reqBody.getJobName()));
        List<Long> idList =
            result.getRecords().stream().map(JobExecutionPageResBody::getJobExecutionId).collect(Collectors.toList());

        List<JobExecutionParams> list =
            jobExecutionParamsMapper.selectList(new QueryWrapper<JobExecutionParams>().in("JOB_EXECUTION_ID", idList));
        Map<Long, String> map = list.stream()
            .collect(Collectors.groupingBy(JobExecutionParams::getJobExecutionId,
                Collectors.mapping(
                    e -> e.getKeyName().concat("=").concat(e.getStringVal() == null ? "null" : e.getStringVal()),
                    Collectors.joining(","))));

        return result.convert(body -> {
            body.setParams(map.get(body.getJobExecutionId()));
            return body;
        });
    }

    @Override
    public List<StepExecutionResBody> queryStepList(Long jobExecutionId) {
        return stepExecutionMapper.selectList(new QueryWrapper<StepExecution>().eq("JOB_EXECUTION_ID", jobExecutionId))
            .stream().map(e -> {
                StepExecutionResBody body = new StepExecutionResBody();
                Beans.copyProperties(e, body);
                return body;
            }).collect(Collectors.toList());
    }

}
